/**
 * 
 */
package com.serial.java;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author LionBule
 *
 */
public class ObjectSerializeGzipUtil {
	
	public static byte[] serialize(Object obj) throws IOException {
		if(obj==null) 
			throw new NullPointerException();
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		OutputStream          os  = new GZIPOutputStream(bos);
		ObjectOutputStream    out = new ObjectOutputStream(os);
		
		out.writeObject(obj);
		out.flush();
		out.close();
		os.close();
		
		byte[] _data = null;
		_data = bos.toByteArray();
		bos = null;
		
		return _data;
	}
	
	public static Object deserialize(byte[] by) throws Exception {
		if(by==null) 
			throw new NullPointerException();
		
		Object _data = null;
		InputStream is = new GZIPInputStream(new ByteArrayInputStream(by));
		ObjectInputStream in = new ObjectInputStream(is);
		_data = in.readObject();
		in.close();
		is.close();
		
		return _data;
	}
}
